from flask import abort
from flask import g
from flask import request
from flask import session, jsonify
from sqlalchemy.testing import in_

from info import constants, db
from info.models import User, Category, News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blue
from flask import render_template, current_app


@news_blue.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg='请先登录')

    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ("add", "remove"):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg='无此评论')

    if action == 'add':
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if not comment_like:
            comment_like = CommentLike()
            comment_like.user_id = g.user.id
            comment_like.comment_id = comment_id
            db.session.add(comment_like)

            comment.like_count += 1
    else:
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库存储失败')

    return jsonify(errno=RET.OK, errmsg='成功')


@news_blue.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='请先登录')

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg='无此用户')

    if action == 'follow':
        if target_user.followers.filter(User.id == user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg='该用户已关注')
        target_user.followers.append(g.user)

    if action == 'unfollow':
        if target_user.followers.filter(User.id == user.id).count() > 0:
            target_user.followers.remove(g.user)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    news_id = request.json.get('news_id')
    comment_str = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻无数据')

    try:
        user_ = User.query.get(user.id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    if not user_:
        return jsonify(errno=RET.NODATA, errmsg='用户无数据')

    comment = Comment()
    comment.user_id = user_.id
    comment.news_id = news.id
    comment.content = comment_str

    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    return jsonify(errno=RET.OK, errmsg='成功', data=comment.to_dict())


@news_blue.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='找不到该新闻')

    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存失败')
    return jsonify(errno=RET.OK, errmsg='成功')


@news_blue.route('/<news_id>')
@user_login_data
def get_news_id(news_id):
    user = g.user

    news_model = None
    try:
        news_model = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    click_news_list = []
    for news in news_model if news_model else []:
        click_news_list.append(news.to_basic_dict())

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    if not news:
        abort(404)

    news.clicks += 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    is_collected = False
    is_followed = False

    if g.user:
        if news in g.user.collection_news:
            is_collected = True
        if news.user:
            if user in news.user.followers:
                is_followed = True

    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_like_ids = []
    if g.user:
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) > 0:
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids), CommentLike.user_id==g.user.id).all()
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]

        except Exception as e:
            current_app.logger.error(e)

    comment_list = []

    for item in comments:
        comment_dict = item.to_dict()
        comment_dict['is_like'] = False
        if g.user and item.id in comment_like_ids:
            comment_dict['is_like'] = True
        comment_list.append(comment_dict)

    # 拼接返回数据字典
    data = {
        'user': user.to_index_dict() if user else None,
        'click_list': click_news_list,
        'news': news.to_dict(),
        'is_collected': is_collected,
        'comment_list': comment_list,
        'is_followed': is_followed
    }
    return render_template('news/detail.html', data=data)
